// 引入数据库实例
const db = require("../utils/mysql.js");
// 引入获取头像
const getHeadImg = require("../utils/getHeadImg");

// 引入密码加密模块
const bcrypt = require("bcryptjs");
// 引入jwt工具
const config = require("../utils/jwt.js");
const dosql = require("../utils/doSql.js");
const update = dosql.updata;
const insert = dosql.insert;
const query = dosql.query;
const v = require("../utils/verify.js")
const v2 = require("../utils/verify2.js")

// 用户注册
exports.saveUser = (req, res) => {
	let userIf = req.body;
	return new Promise(async (resolve, reject) => {
		// 首先查询该用户注册了没有
		const sql1 = `select * from user where username = ?`;

		db.query(sql1, [userIf.username], function (err, results) {
			if (err) {
				return res.sd(err.message);
			}
			// 名被占用
			if (results.length > 0) {
				return res.sd("已经注册过了");
			}
			resolve();
		})
	}).then(async () => {
		let imgurl = await getHeadImg(userIf.username);
		// 加密密码
		// 对用户的密码,进行 bcrype 加密，返回值是加密之后的密码字符串,(密码明文, 加密盐长度)
		userIf.password = bcrypt.hashSync(userIf.password, 10);
		const sql2 = `insert into user set ?`;
		// 注意：req 对象上的 user 属性，是 Token 解析成功，express-jwt 中间件帮我们挂载上去的
		db.query(sql2,
			{
				name: imgurl.name || "热心肠网友",
				username: userIf.username,
				password: userIf.password,
				touxiang: imgurl.imgurl,
			},
			(err, results) => {
				// 1. 执行 SQL 语句失败
				if (err) {
					return res.sd(err);
				}
				// 2. 执行 SQL 语句成功，但是查询到的数据条数少于0
				// console.log('#',results.length);
				if (results.affectedRows !== 1) {
					return res.sd("注册失败！");
				}

				// 3. 将信息响应给客户端
				res.sd("成功", 0);

			});
	}).catch((err) => {
		res.sd(err);
	});
};

// 用户登陆
exports.login = async (req, res) => {

	const userinfo = req.body;
	if (!userinfo.password || !userinfo.username) {
		return res.sdErr("登陆失败! 检查参数是否为空!");
	}
	const sql = `select * from user where username=? and password = ?`;
	try {
		// 查询数据库中的信息
		let results = await query(sql, [userinfo.username, userinfo.password])
		const user = { ...results[0], password: "" };

		res.sd(config.getToken(user));
	} catch (e) {
		res.sdErr(e)
	}
};


// 用户信息
exports.info = async (req, res) => {
	try {
		let token = req.headers.token;
		let username = config.verifyToken(token).username;
		let sql = `
		SELECT u.touxiang as touxiang,u.user_id,u.username as username,u.name AS name,
		GROUP_CONCAT(DISTINCT CASE WHEN SUBSTRING(m.routes, 1, 1) <> '_' THEN m.routes END SEPARATOR ',') AS routes,
		GROUP_CONCAT(DISTINCT CASE WHEN SUBSTRING(m.routes, 1, 1) = '_' THEN m.routes END SEPARATOR ',') AS buttons
	  FROM user u
	  LEFT JOIN user_role ur ON u.user_id = ur.user_id
	  LEFT JOIN role r ON ur.role_id = r.role_id
	  LEFT JOIN role_menu rm ON r.role_id = rm.role_id
	  LEFT JOIN menu m ON rm.menu_id = m.menu_id
	  WHERE u.username = ?
	  GROUP BY u.user_id;
		`
		let result = await query(sql, [username]);
		if (!token || !username) {
			res.sdErr("Invalid~~~~~~~~~");
		} else {
			res.sd(result[0]);
		}
	} catch (e) {
		res.sdErr("错了");
	}


};

// 查询所有用户以及所属角色
exports.allUser = async (req, res) => {
	if (v(req, ["pageNo"], res) !== 0) {
		return;
	}
	let pageNo = Number(req.query.pageNo);
	const sql = `
	select u.user_id,u.name,u.username,u.password,u.mail,GROUP_CONCAT(r.role_name SEPARATOR ',') AS roles,GROUP_CONCAT(r.role_id SEPARATOR ',') as role_id
from user u
left join user_role ur on u.user_id = ur.user_id
left join role r on ur.role_id = r.role_id
where u.exist=1
group by u.user_id
limit 10 offset ?;
	`
	try {
		let result = await query(sql, [pageNo]);
		res.sd(result);
	} catch (e) {
		res.sdErr(e);
	}
};

// 查询符合角色
exports.searchUser = async (req, res) => {
	if (v(req, ["pageNo", "name"], res) !== 0) {
		return;
	}

	let pageNo = Number(req.query.pageNo);
	let name = req.query.name;
	console.log(pageNo, name);
	const sql = `
	select u.user_id,u.name,u.username,u.password,u.mail,GROUP_CONCAT(r.role_name SEPARATOR ',') AS roles,GROUP_CONCAT(r.role_id SEPARATOR ',') as role_id
	from user u
	left join user_role ur on u.user_id = ur.user_id
	left join role r on ur.role_id = r.role_id
	where name like ?
	and u.exist=1
	group by u.user_id
	limit 10 offset ?;
	`
	try {
		let result = await query(sql, [`%${name}%`, pageNo]);
		res.sd(result);
	} catch (e) {
		res.sdErr(e);
	}
};

// 查询所有用户数量
exports.userCount = async (req, res) => {
	let userid = req.body.user_id;
	const sql = `
	select count(*) as count from user where exist = 1;
	`
	try {
		let result = await query(sql);
		res.sd(result[0].count);
	} catch (e) {
		res.sdErr(e);
	}
};


// 添加用户
exports.addUser = async (req, res) => {
	if (v2(req, ["name", "username", "password", "mail"], res) !== 0) {
		return;
	}
	let name = req.body.name;
	let username = req.body.username;
	let password = req.body.password;
	let mail = req.body.mail;
	const sql = `
	select * from user where username = ?
	`
	try {
		let result = await query(sql, [username]);
		if (result.length > 0) {
			res.sdErr("已经有这个用户了!")
		} else {
			const sql1 = `insert into user (name, username, password, mail) values (?,?,?,?);`
			await update(sql1, [name, username, password, mail])
			res.sd("ok");
		}
	} catch (e) {
		res.sdErr(e);
	}
};

// 删除用户
exports.delUser = async (req, res) => {

	if (v2(req, ["user_id"], res) !== 0) {
		return;
	}
	let user_id = req.body.user_id;
	const sql = `
	update user set exist = 0
where user_id = ?;
	`
	try {
		await update(sql, [user_id]);
		res.sd("ok");
	} catch (e) {
		res.sdErr(e);
	}
};
// 批量删除用户
exports.delMoreUser = async (req, res) => {
	const delUser = async (users) => {
		const sql = `
			update user set exist = 0
		where user_id = ?;
			`
		for (let i = 0; i < users.length; i++) {
			let user = users[i];
			await update(sql, [user]);
		}
	}
	try {
		let users = req.body.user_id;
		await delUser(users);
		res.sd("ok");
	} catch (e) {
		res.sdErr(e);
	}



};

// 修改用户信息
exports.upUser = async (req, res) => {
	if (v2(req, ["user_id", "name", "username", "password", "mail"], res) !== 0) {
		return;
	}
	let name = req.body.name;
	let username = req.body.username;
	let password = req.body.password;
	let mail = req.body.mail;
	let user_id = req.body.user_id;
	// 首先排除账号一致风险
	const sql0 = `select * from user where username=?`
	let result = await query(sql0, [username]);
	if (result.length > 1) {
		res.sdErr("账号已存在!")

	} else {
		const sql = `
		update user set name=?,username=?,password=?,mail=?
	where user_id=?;
		`
		try {
			await update(sql, [name, username, password, mail, user_id]);
			res.sd("ok");
		} catch (e) {
			res.sdErr(e);
		}
	}

};

// 查询所有角色
exports.allRole = async (req, res) => {
	let userid = req.body.user_id;
	const sql = `
	select role_id,role_name from role where exist = 1;
	`
	try {
		let result = await query(sql);
		res.sd(result);
	} catch (e) {
		res.sdErr(e);
	}
};

// 修改用户角色
exports.upRole = async (req, res) => {
	if (v2(req, ["user_id"], res) !== 0) {
		return;
	}
	const addRole = async (user_id, role_ids) => {
		const sql0 = `insert into user_role (user_id, role_id) values (?, ?)`;
		for (let i = 0; i < role_ids.length; i++) {
			let role = role_ids[i];
			await update(sql0, [user_id, role])
		}

	}
	const delRole = async (user_id, role_ids) => {
		const sql0 = `delete from user_role where user_id=? and role_id = ?`
		for (let i = 0; i < role_ids.length; i++) {
			let role = role_ids[i];
			await update(sql0, [user_id, role])
		}
	}
	let role_id = req.body.role_id;
	let user_id = req.body.user_id;
	// 首先查询这个用户有没有角色
	const sql = `select * from user_role where user_id=?`
	let result = await query(sql, [user_id]);
	// 如果没有角色 直接创建
	if (result.length < 1) {
		await addRole(user_id, role_id);
		res.sd("ok");
		return;
	}
	// 说明这个用户有角色
	const sql1 = `select role_id from user_role where user_id = ?`
	let result2 = await query(sql1, [user_id]);
	// 查询出该用户已有的角色 筛选
	let resArr = result2.map((item) => item.role_id);
	// 获取跟原先对比, 没有了的角色, 跟新增的角色
	const missingElements = resArr.filter((element) => !new Set(role_id).has(element));
	const newElements = role_id.filter((element) => !new Set(resArr).has(element));
	try {
		// 首先处理减少的职位
		await delRole(user_id, missingElements);
		// 然后处理增加的职位
		await addRole(user_id, newElements)
		res.sd("ok")
	} catch (e) {
		res.sdErr(e);
	}
};


// 添加角色
exports.addRole = async (req, res) => {
	if (v2(req, ["role_name"], res) !== 0) {
		return;
	}
	let role_name = req.body.role_name;
	const sql = `
	insert into role (role_name) values (?);
	`
	try {
		await insert(sql, [role_name]);
		res.sd("ok");
	} catch (e) {
		res.sdErr(e);
	}
};

// 搜索角色
exports.searchRole = async (req, res) => {
	let role_name = req.query.role_name;
	console.log(role_name);
	const sql = `
	select role_id,role_name
from role
where role_name like ?
and exist = 1;
	`
	try {
		let result = await query(sql, [`%${role_name}%`]);
		res.sd(result);
	} catch (e) {
		res.sdErr(e);
	}
};

// 删除角色
exports.delRole = async (req, res) => {
	if (v2(req, ["role_id"], res) !== 0) {
		return;
	}
	let role_id = req.body.role_id;
	const sql = `
	update role set exist = 0 where role_id = ?;
	`
	try {
		await update(sql, [role_id]);
		res.sd("ok");
	} catch (e) {
		res.sdErr(e);
	}
};

// 修改角色
exports.chRole = async (req, res) => {
	if (v2(req, ["role_name", "role_id"], res) !== 0) {
		return;
	}
	let role_name = req.body.role_name;
	let role_id = req.body.role_id;
	const sql = `
	update role set role_name = ? where role_id = ?;
	`
	try {
		await update(sql, [role_name, role_id]);
		res.sd("ok");
	} catch (e) {
		res.sdErr(e);
	}
};

